package com.heze.xunhuan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heze.xunhuan.entity.AuditLog;
import com.heze.xunhuan.entity.Post;
import com.heze.xunhuan.entity.User;
import com.heze.xunhuan.exception.BusinessException;
import com.heze.xunhuan.mapper.AuditLogMapper;
import com.heze.xunhuan.mapper.PostMapper;
import com.heze.xunhuan.mapper.UserMapper;
import com.heze.xunhuan.service.AdminService;
import com.heze.xunhuan.service.PostService;
import com.heze.xunhuan.vo.PageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 管理后台服务实现类
 *
 * @author heze-xunhuan
 */
@Service
@RequiredArgsConstructor
public class AdminServiceImpl implements AdminService {

    private final UserMapper userMapper;
    private final PostMapper postMapper;
    private final PostService postService;
    private final AuditLogMapper auditLogMapper;

    @Override
    public Map<String, Object> getDashboardOverview() {
        Map<String, Object> overview = new HashMap<>();

        // 用户统计
        Map<String, Object> userStats = new HashMap<>();
        long totalUsers = userMapper.selectCount(null);
        LambdaQueryWrapper<User> todayUserWrapper = new LambdaQueryWrapper<>();
        todayUserWrapper.apply("DATE(created_at) = CURDATE()");
        long todayNewUsers = userMapper.selectCount(todayUserWrapper);
        userStats.put("totalUsers", totalUsers);
        userStats.put("todayNewUsers", todayNewUsers);
        userStats.put("activeUsers", 0); // TODO: 实现活跃用户统计
        overview.put("userStats", userStats);

        // 信息统计
        Map<String, Object> postStats = new HashMap<>();
        long totalPosts = postMapper.selectCount(null);
        LambdaQueryWrapper<Post> todayPostWrapper = new LambdaQueryWrapper<>();
        todayPostWrapper.apply("DATE(created_at) = CURDATE()");
        long todayPosts = postMapper.selectCount(todayPostWrapper);
        LambdaQueryWrapper<Post> approvedWrapper = new LambdaQueryWrapper<>();
        approvedWrapper.eq(Post::getStatus, "approved");
        long approvedPosts = postMapper.selectCount(approvedWrapper);
        double approvalRate = totalPosts > 0 ? (approvedPosts * 100.0 / totalPosts) : 0;
        postStats.put("totalPosts", totalPosts);
        postStats.put("todayPosts", todayPosts);
        postStats.put("approvalRate", approvalRate);
        overview.put("postStats", postStats);

        // 业务统计
        Map<String, Object> businessStats = new HashMap<>();
        businessStats.put("totalTransactions", 0); // TODO: 实现交易统计
        businessStats.put("todayContacts", 0); // TODO: 实现联系统计
        overview.put("businessStats", businessStats);

        return overview;
    }

    @Override
    public PageVO<Post> getPendingPosts(Integer page, Integer size) {
        Page<Post> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Post::getStatus, "pending");
        wrapper.orderByDesc(Post::getCreatedAt);

        IPage<Post> postPage = postService.page(pageParam, wrapper);
        return new PageVO<>(postPage.getRecords(), page, size, postPage.getTotal());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void auditPost(Long postId, Long adminUserId, String action, String reason) {
        Post post = postService.getById(postId);
        if (post == null) {
            throw new BusinessException(404, "信息不存在");
        }

        String oldStatus = post.getStatus();
        String newStatus = "approve".equals(action) ? "approved" : "rejected";

        post.setStatus(newStatus);
        if ("rejected".equals(newStatus)) {
            post.setRejectReason(reason);
        } else {
            post.setApprovedAt(LocalDateTime.now());
        }
        postService.updateById(post);

        // 记录审核日志
        AuditLog auditLog = new AuditLog();
        auditLog.setAdminUserId(adminUserId);
        auditLog.setPostId(postId);
        auditLog.setOldStatus(oldStatus);
        auditLog.setNewStatus(newStatus);
        auditLog.setReason(reason);
        auditLog.setCreatedAt(LocalDateTime.now());
        auditLogMapper.insert(auditLog);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchAuditPosts(Long[] postIds, Long adminUserId, String action, String reason) {
        for (Long postId : postIds) {
            auditPost(postId, adminUserId, action, reason);
        }
    }
}

